package edu.jvn.ict.locationsharing.informationexchange;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import edu.jvn.ict.locationsharing.GPSCoordinate;
import edu.jvn.ict.locationsharing.MemberInfo;
import edu.jvn.ict.locationsharing.MemberServer;
import edu.jvn.ict.locationsharing.Utility;

public class UpdateLocationMessage extends ExchangeMessage {
	/**
	 * 
	 */
	public static final int MESSAGE_ID = 8;
	private static final long serialVersionUID = 3777438461188250912L;
	private long nodeId;
	private GPSCoordinate gpsCoordinate;
	private long timeStamp; // taken when package sent out

	public long getNodeId() {
		return nodeId;
	}

	public void setNodeId(long nodeId) {
		this.nodeId = nodeId;
	}

	public GPSCoordinate getGpsCoordinate() {
		return gpsCoordinate;
	}

	public void setGpsCoordinate(GPSCoordinate gpsCoordinate) {
		this.gpsCoordinate = gpsCoordinate;
	}

	public long getTimeStamp() {
		return timeStamp;
	}

	public void setTimeStamp(long timeStamp) {
		this.timeStamp = timeStamp;
	}

	@Override
	public void process(ObjectInputStream in, ObjectOutputStream out)
			throws IOException {
		if (MemberServer.map != null) {
			MemberInfo memberInfo = MemberServer.map.get(nodeId);
			if (memberInfo != null) {
				memberInfo.setGpsCoordinate(gpsCoordinate);
				memberInfo.setGpsTimestamp(timeStamp);
			} else {
				System.out.println("No member with nodeID");
			}
		}

		MemberServer.exchangeInformation(this, 1, false);
	}

	public String toString() {
		return Utility.APP_START_MESSAGE + Integer.toString(MESSAGE_ID) + ","
				+ Long.toString(nodeId) + ","
				+ Double.toString(gpsCoordinate.getAltitude()) + ","
				+ Double.toString(gpsCoordinate.getLatitude()) + ","
				+ Double.toString(gpsCoordinate.getLongitude()) + ","
				+ Long.toString(timeStamp);
	}

	public UpdateLocationMessage(String message) {
		String[] split = message.split(",");
		nodeId = Long.parseLong(split[0]);
		double altitude = Double.parseDouble(split[1]);
		double latitude = Double.parseDouble(split[2]);
		double longitude = Double.parseDouble(split[3]);
		gpsCoordinate = new GPSCoordinate(altitude, latitude, longitude);
		timeStamp = Long.parseLong(split[4]);
	}

	public UpdateLocationMessage() {
		gpsCoordinate = new GPSCoordinate(1, 1, 1);
	}

}
